<?php
defined('PT_ACCESS') or die('No direct access');

class Controller{

	protected $htcontent = NULL;

	public function __construct(){
		$this->htaccess();
	}

	public function htaccess($hta = '.htaccess'){
		if (file_exists(APP_ROOT . $hta))
			$this->htcontent = file_get_contents(APP_ROOT . $hta);

		if (!file_exists(APP_ROOT . $hta) || !stristr($this->htcontent, 'RewriteEngine on')){
			$errorMessage = '<h2>Mod-Rewrite is required. Please enable Mod-Rewrite in the file called <i>.htaccess</i>';
			die($errorMessage);
		}
	}

	public function forward($page, $action, $switch = ''){
		// Login admin control panel
		if ($switch == ADMIN or $switch == 'adlogin'){
			$file = ADMIN_CONTROLLERS . $page . '.php';
		}else{
			// This is font page
			$file = DIR_CONTROLLERS . $page . '.php';
		}

//		echo '<pre>';
//		echo $file;
//		print_r(get_required_files());
//		echo '</pre>';

		if (!file_exists($file)){
			$this->forward('error', 'notFound');
			exit();
		}

		require $file;

		$controller = new $page();
		$controller->setName($page);
		$controller->dispatchAction($action, $switch);
		exit(0);
	}

	public function redirect($page, $action, $switch = '') {
		if ($switch == ADMIN)
			$url = '/' . ADMIN . '/';
		else
			$url = '/';

  		$location = BASE_URL . $url . '?page=' . $page . '&action=' . $action;
//	  	echo $location;
		header('HTTP/1.1 301 Moved Permanently');
  		header('Location: ' . $location);
  		exit();
  	}
}